<?php
namespace Admin\Model;
use Think\Model;
use Think\Model\RelationModel;

/**
 * 商品模型类
 */
class OrderModel extends RelationModel{

	protected $_link = array(
        'OrderDetail'=>array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'OrderDetail',
            'mapping_name' => 'detaillist',
            'foreign_key' => 'order_id'
            )
    );

	protected $_validate = array(
            array('customers_id','require','请选择客户！'),
        );

    /* 自动完成规则 */
    protected $_auto = array(
        array('status', 1, self::MODEL_INSERT, 'string'),
        array('orderdate', 'time', self::MODEL_INSERT, 'function'),
        array('create_time', 'time', self::MODEL_INSERT, 'function'),
        array('update_time', 'time', self::MODEL_BOTH, 'function'),
    );

    /**
     * 提交订单
     * @return boolean fasle 失败 ， int  成功 返回完整的数据
     * @author RickChan
     */
    public function submitOrder(){
        /* 获取数据对象 */
        $Order = D("Order");
        $data = $this->create($_POST);
        if(empty($data)){
            return false;
        }
        $data["ordernum"] = $this->createOrderNum();
        //获取接单员信息
        $adminuser = $_SESSION['onethink_admin']['user_auth'];
        $data["jdy_id"] = $adminuser['uid'];
        $data["jdy_name"] = $adminuser['username'];

        $cart = $_SESSION['cart'];
        $goodslist = $cart['goods_list'];
        if(count($goodslist) == 0 ){
            $this->error = '购物车没有任何商品！';
            return false;
        }
        $detaillist = array();
        foreach ($goodslist as $goods) {
        	$OrderDetail["spe_id"] = $goods["spe_id"];
        	$OrderDetail["spe_name"] = $goods["spe_name"];
        	$OrderDetail["goods_name"] = $goods["goods_name"];
        	$OrderDetail["goods_id"] = $goods["goods_id"];
            $OrderDetail["type_id"] = $goods["type_id"];
            $OrderDetail["type_name"] = $goods["type_name"];
        	$OrderDetail["unit"] = $goods["unit"];
        	$OrderDetail["num"] = $goods["num"];
        	$OrderDetail["price"] = $goods["price"];
        	$OrderDetail["total"] = $goods["total"];
        	array_push($detaillist, $OrderDetail);
        }
        $data["detaillist"] = $detaillist;
        $data["total"] = $cart["total_price"];

        $OrderDetail = D("OrderDetail");
        $result = $Order->relation(true)->add($data);
        if(!$result){
            $this->error = '提交订单出错！';
            return false;
        }
        return $result;
    }

    public function createOrderNum(){
    	$Order = M("Order");
    	$date = date('Ym');
        $start=strtotime(date('Y-m-01 00:00:00'));
        $end = strtotime(date('Y-m-d H:i:s'));
        $map['create_time'] = array('between',array($start,$end));
    	$ocount = $Order->where($map)->count();
        $var =  $Order->getLastSql();
    	$temp_num = 1000000;
    	$new_num = $temp_num + $ocount + 1;
    	$ordernum = $date.substr($new_num, 1,6);
    	return $ordernum;
    }
}